package cn.com.zpark.dbcp;

import org.apache.commons.dbcp.BasicDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * @PackageName: cn.com.zpark.dbcp
 * @ClassName: DBCPUtils01
 * @Description:DBCP数据库连接池
 * @author: RZS
 * @date: 2021/10/31  16:34
 */
public class DBCPUtils01 {
    private static String driver;
    private static String url;
    private static String username;
    private static String password;

    // 定义数据源
    private static BasicDataSource dataSource;

    /**
     * 初始化资源
     */
    static {
        url = "jdbc:mysql://192.168.80.142:3306/mydb1?useSSL=false&serverTimezone=UTC&characterEncoding=UTF-8";
        driver = "com.mysql.jdbc.Driver";
        username = "root";
        password = "root";

        dataSource = new BasicDataSource();
        dataSource.setDriverClassName(driver);
        dataSource.setUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(password);

    }

    /**
     * 获取连接对象
     */
    public static Connection getConn() throws Exception {
        return dataSource.getConnection();
    }

    /**
     * 关闭连接
     */
    public static void close(ResultSet res, Connection conn, Statement... stat){
        if (res != null) {
            try {
                res.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        /**************可变参数*************/

        for (Statement statement : stat) {
            if(statement != null){
                try {
                    statement.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }

        /**************可变参数*************/


        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
